package com.fwtai.service.api;

import com.fwtai.api.ApiShareDao;
import com.fwtai.bean.PageFormData;
import com.fwtai.config.ConfigFile;
import com.fwtai.config.LocalUserId;
import com.fwtai.tool.ToolClient;
import com.fwtai.tool.ToolCode;
import com.fwtai.tool.ToolString;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 分享推广业务层
 * @作者 田应平
 * @版本 v1.0
 * @QQ号码 444141300
 * @创建日期 2021-09-14 11:46:52
 * @官网 <url>http://www.fwtai.com</url>
*/
@Service
public class ApiShareService{

  @Value("${share_url}")
  private String shareUrl;

  @Resource
  private ApiShareDao apiShareDao;

  /*todo
      1.处理逻辑：
      在生成推广二维码时查询自己是否在分享的关系表'share_relation'中有记录?
      (1).有记录,仅生成自己的推广二维码即可；
      (2).无记录,生成自己的推广二维码且在分享关系表'share_relation'中添加1条记录根节点!
      2.在注册添加用户时处理注册时的逻辑：
      判断是否有推广的二维码？
      (1).无推广码不处理
      (2).有推广码，处理自己与该二维码的分享者的上下级关系即可
  */
  public synchronized String queryCode(final String userId){
    final String loginId = userId == null ? LocalUserId.get() : userId;//userId为空时获取自己的邀请码并生产关系树
    final HashMap<String,Object> map = apiShareDao.queryCode(loginId);
    if(map == null){
      while (true){
        final String[] shorts = ToolCode.generator();
        for(final String code : shorts){
          if(queryCodeExist(code)){
            final PageFormData formData = new PageFormData();
            formData.put("loginId",loginId);
            formData.put("code",code);
            final String url = shareUrl + code;
            formData.put("url",url);
            final int rows = apiShareDao.add(formData);
            return handerResult(rows,url,code);
          }
        }
      }
    }
    return ToolClient.queryJson(map);
  }

  private String handerResult(final int rows,final String url,final String code){
    if(rows > 0){
      final HashMap<String,String> result = new HashMap<>(2);
      result.put("url",url);
      result.put("code",code);
      return ToolClient.queryJson(result);
    }else{
      return ToolClient.createJsonFail("生成分享链接失败,稍候重试!");
    }
  }

  /**
   * 查询邀请码是否已存在
   * @作者 田应平
   * @QQ 444141300
   * @创建时间 2019/7/29 15:11
   */
  private boolean queryCodeExist(final String code){
    return apiShareDao.queryCodeExist(code) == null;
  }

  public String listDataPage(final HttpServletRequest request){
    final PageFormData formData = ToolClient.pageParamsApi(request);
    if(formData == null) return ToolClient.jsonValidateField();
    final String loginId = LocalUserId.get();
    formData.put("loginId",loginId);
    final HashMap<String,Object> map = apiShareDao.listDataPage(formData);
    final List<Map<String,Object>> list = (List<Map<String,Object>>) map.get(ConfigFile.rows);
    list.forEach(item->{
      item.put("telephone",ToolString.replacePhone((String) item.get("telephone")));
    });
    return ToolClient.jsonPage(list,(Integer) map.get(ConfigFile.total));
  }

  public String getIdentity(){
    final String loginId = LocalUserId.get();
    if(loginId == null){
      return ToolClient.accessLogin();
    }
    return ToolClient.queryJson(apiShareDao.getIdentity(loginId));
  }

  public String getMyTeamList(final HttpServletRequest request){
    final String loginId = LocalUserId.get();
    if(loginId == null){
      return ToolClient.accessLogin();
    }
    final PageFormData formData = ToolClient.pageParamsApi(request);
    if(formData == null) return ToolClient.jsonValidateField();
    formData.put("loginId",loginId);
    final List<Map<String,Object>> list = apiShareDao.getMyTeamList(formData);
    /*list.forEach(map->{
       map.put("user_name",ToolString.replacePhone((String) map.get("user_name")));
    });*/
    return ToolClient.jsonPage(list);
  }

  public String getMyTotal(){
    final String loginId = LocalUserId.get();
    if(loginId == null){
      return ToolClient.accessLogin();
    }
    final Integer nextInfo = apiShareDao.getNextInfo(Long.parseLong(loginId));//间接客户,我的下级邀请的下级
    return ToolClient.queryJson(nextInfo);
  }

  public String getMyInviter(){
    final String loginId = LocalUserId.get();
    if(loginId == null){
      return ToolClient.accessLogin();
    }
    final HashMap<String,Object> list = apiShareDao.getMyInviter(Long.parseLong(loginId));
    return ToolClient.queryJson(list);
  }
}